<?php
function getCityFromZipCode($zipcode) {
 #download html
 ob_start();
 readfile("http://www.posten.se/soktjanst/postnummersok/resultat.jspv?pnr=$zipcode");
 $raw_data = ob_get_clean();
 #start parsing hack
 $lines = explode("\n",$raw_data);
 foreach ($lines as $line) {
  #<TR class="even"><TD class="firstcol">street</TD><TD>something</TD><TD>zipcode</TD><TD class="lastcol">city</TD></TR>
  if (preg_match("/<TR\b[^>]*><TD\b[^>]*>(.*?)<\/TD><TD\b[^>]*>(.*?)<\/TD><TD\b[^>]*>(.*?)<\/TD><TD\b[^>]*>(.*?)<\/TD><\/TR>/", $line, $matches)) {
   return $matches[4];
  }
 }
 return false;
}

function store($zip,$city) {
 print "Storing $zip with $city\n";
 system("echo \"$zip;$city\" >> zipcodes.csv");
}

system("echo '' > zipcodes.csv");

for ($i = 10000; $i < 99999; $i++) {
 list($zipcode,$city) = explode(",",$city_line);
 $city = getCityFromZipCode($i);
 if ($city == false)
  print "$i not found\n";
 else
  store($i,$city);
}
?>
